package com.lagou.upload.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.lagou.entity.FileSystem;
import com.lagou.upload.FileService;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@Service //暴露服务
public class FileServiceImpl implements FileService {
    @Autowired
    private RedissonClient redisson;

    @Override
    public FileSystem upload(byte[] pic, String fileName) {
        System.out.println("进入文件上传。。。");
        FileSystem fileSystem=new FileSystem();
        // 从文件对象中获取 文件的原始名称
        String oldFileName = fileName;
        // 通过redisson获取锁
        RLock rLock = redisson.getLock(oldFileName); // 底层源码就是集成了setnx，过期时间等操作
        // 上锁（过期时间为30秒）
        rLock.lock(30, TimeUnit.SECONDS);
        try {
            String hou = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
            /* 1、把文件上传到FastDFS*/
            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = null;
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);

            NameValuePair[] list = new NameValuePair[1];
            list[0] = new NameValuePair("fileName",oldFileName);
            String fileId = client.upload_file1(pic, hou, list);
            trackerServer.close();
            // 封装fileSystem数据对象
            fileSystem.setFileId(fileId);
            fileSystem.setFileName(oldFileName);
            fileSystem.setFilePath(fileId);  //已经上传到FastDFS上，通过fileId来访问图片，所以fileId即为文件路径
        } catch (IOException | IllegalStateException | MyException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            rLock.unlock();
        }
        return fileSystem;
    }
}
